package com.situ.mall.controller.front;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.entity.Cart;
import com.situ.mall.entity.Order;
import com.situ.mall.entity.OrderItem;
import com.situ.mall.entity.Shipping;
import com.situ.mall.entity.User;
import com.situ.mall.service.ICartService;
import com.situ.mall.service.IOrderItemService;
import com.situ.mall.service.IOrderService;
import com.situ.mall.service.IShippingService;

@Controller
@RequestMapping("/order")
public class FrontOrderController {

	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private IOrderItemService orderItemService;
	
	@Autowired
	private IShippingService shippingService;
	
	@Autowired
	private ICartService cartService;
	
	@RequestMapping("/getPlaceOrder.shtml")
	public String getPlaceOrder(HttpSession session,Model model) {
		User user = (User) session.getAttribute("user");
		Shipping shipping = shippingService.selectShippingByUserId(user.getId());
		model.addAttribute("shipping", shipping);
		List<Cart> carts = cartService.selectCartByUserIdAndChecked(user.getId());
		session.setAttribute("carts", carts);
		model.addAttribute("carts", carts);
		return "place_order";
	}
	
	@RequestMapping("/getUserCenterOrder.shtml")
	public String getUserCenterOrder(HttpSession session,Model model) {
		User user = (User) session.getAttribute("user");
		List<Order> orders = orderService.selectOrderByUserId(user.getId());
		model.addAttribute("orders", orders);
		List<OrderItem> orderItems = orderItemService.selectOrderItemByUserId(user.getId());
		model.addAttribute("orderItems", orderItems);
		return "user_center_order";
	}
	
	@RequestMapping("/insertOrder.shtml")
	@ResponseBody
	public ServerResponse insertOrder(HttpSession session,Integer shippingId,Integer paymentType,Double payment) {
		int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
		int r2=(int)(Math.random()*(10));
		long now = System.currentTimeMillis();//一个13位的时间戳
		String orderID =String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now);// 订单ID
		Long orderNo= Long.parseLong(orderID);
		
		BigDecimal paymentBigDecimal = new BigDecimal(payment.toString());
		
		orderItemService.insertOrderItem(orderNo, session);
		
		return orderService.insertOrder(orderNo,session,shippingId,paymentType,paymentBigDecimal);
	}
	
}
